package by.kniazhych.core.controllers.actions {
	
	/**
	 * ...
	 * @author Boutylin Mikhail
	 */
	
		import by.kniazhych.core.controllers.AbstractServerAction;
	import by.kniazhych.core.controllers.GameController;
	import by.kniazhych.core.data.game.PeaceData;
	import by.kniazhych.core.data.game.PeacePosition;
	import by.kniazhych.core.events.GameEvent;
	import by.kniazhych.core.events.ViewEvent;
	import flash.events.Event;
	

	
	public class ProcessMotionAction extends AbstractServerAction{
		private var arr:Array;
		
		public function ProcessMotionAction(target:GameController, sP:PeacePosition, fP:PeacePosition) {
			super(target);
			arr = new Array();
			arr.push.apply(null, arguments);
			arr.shift();
			
		}
		
		override public function process():void {
			_process.apply(null, this.arr);
			_gameContainer.addEventListener(ViewEvent.RENDERED, _onMotionRendered);
		}
		
		private function _process(sP:PeacePosition, fP:PeacePosition):void {
			var fpString:String = fP.y + ":" + fP.x;
			var spString:String = sP.y + ":" + sP.x;
			var data:PeaceData = PeaceData(super._peaceLinker[spString]);
			
			if (sP.x != fP.x || sP.y != fP.y) {
				if (super._peaceLinker[fpString]) {
					super._gameData.removeChild(super._peaceLinker[fpString] as PeaceData);
				}
				data.setPosition(fP.x, fP.y);
				delete super._peaceLinker[spString];
				super._peaceLinker[fpString] = data;				
			}else {
				data.setPosition(fP.x, fP.y);
			}
			
		}
		
		private function _onMotionRendered(e:Event):void {
			_gameContainer.removeEventListener(ViewEvent.RENDERED, _onMotionRendered);
			dispatchEvent(new GameEvent(GameEvent.ACTION_PROCESSED));
		}
	}

}